package com.example.springboot159.config;

import com.example.springboot159.Interceptors.RequireInterceptor;
import com.example.springboot159.Interceptors.XssInterceptor;
import com.example.springboot159.annotation.XssRequired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ObjectToStringHttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.nio.charset.Charset;
import java.util.List;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private Environment environment;


    @Bean
    public XssInterceptor xssRequiredBean(){
        return new XssInterceptor();
    }

    @Bean
    public RequireInterceptor requireInterceptor(){
        return new RequireInterceptor();
    }
    /**
     * 解决跨域问题
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/")
                .allowedOrigins("*")
                .allowedMethods("POST","GET")
                .allowCredentials(true)
                .maxAge(7200);
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(xssRequiredBean());
        registry.addInterceptor(requireInterceptor());
    }


    /**
     * 解决数据转换的问题
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new StringHttpMessageConverter(Charset.forName("utf-8")));
        converters.add(new MappingJackson2HttpMessageConverter());
        converters.add(new ObjectToStringHttpMessageConverter(new DefaultFormattingConversionService(),Charset.forName("utf-8")));
        converters.add(new ResourceHttpMessageConverter());
    }

}
